//
//  AddBiaoQianViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/24.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "AddBiaoQianViewController.h"

@interface AddBiaoQianViewController ()
//@property(nonatomic,copy)NSMutableArray *dataArray;
@property(nonatomic,copy)NSMutableArray *customArray;
@property(nonatomic,copy)NSMutableArray *systemArray;
@property(nonatomic,copy)NSArray *mySystemArray;
@property(nonatomic,copy)UIScrollView *customScrollView;
@property(nonatomic,copy)UIScrollView *systemScrollView;
//@property(nonatomic,copy)UIScrollView *myScrollView;
@property(nonatomic,copy)UIButton *addCustomBiaoQianBtn;
@property(nonatomic,copy)NSTimer *myTimer;
@end

@implementation AddBiaoQianViewController
static int myTime=0;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:234/255.0 green:235/255.0 blue:236/255.0 alpha:1];
    [self.view addSubview:[UIView new]];
    [self initData];
    [self createNavigation];
    [self createUI];
    // Do any additional setup after loading the view.
}
-(void)initData
{
//    NSArray *arr1=@[@"健康达人健康达人健康1",@"美食达人2",@"蔬菜达人3",@"水果达人4",@"健康达人5",@"美食达人6",@"蔬菜达人7"];
    NSArray *arr2=[NSArray arrayWithArray:_tagsArray];
    //NSLog(@"=========tags============%@",_tagsArray);
    NSArray *arr3=[NSArray arrayWithArray:_allSystemArray];
    _customArray=[NSMutableArray arrayWithArray:arr2];
    _systemArray=[NSMutableArray arrayWithArray:arr3];
    _mySystemArray=[NSArray arrayWithArray:arr3];
}
-(void)createUI
{
    
    
    UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 20+44, self.view.frame.size.width, self.view.frame.size.height-20-44)];
    scrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:scrollView];
    
    //CGFloat btn_w=(self.view.frame.size.width-20*3)/2.0;
    CGFloat btn_h=30;
    UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    view1.backgroundColor=[UIColor whiteColor];
    [scrollView addSubview:view1];
    //自定义标签
    UILabel *customBiaoQianLab=[[UILabel alloc]initWithFrame:CGRectMake(15, view1.frame.origin.y+10, 60, 30)];
    customBiaoQianLab.text=@"我的标签";
    customBiaoQianLab.textColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
    customBiaoQianLab.font=[UIFont systemFontOfSize:20];
    customBiaoQianLab.frame=CGRectMake(15, view1.frame.origin.y+10, [customBiaoQianLab calculateWidthWithLable:customBiaoQianLab], 30);
    [scrollView addSubview:customBiaoQianLab];
    
    //添加自定义标签
    UILabel *addcustomBiaoQianLab=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width-20-40, customBiaoQianLab.frame.origin.y, 40, 30)];
    addcustomBiaoQianLab.text=@"添加";
    addcustomBiaoQianLab.textColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
    addcustomBiaoQianLab.textAlignment=NSTextAlignmentRight;
    addcustomBiaoQianLab.font=[UIFont systemFontOfSize:20];
    [scrollView addSubview:addcustomBiaoQianLab];
    
    UIButton *addcustomBiaoQianBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    addcustomBiaoQianBtn.frame=addcustomBiaoQianLab.frame;
    [addcustomBiaoQianBtn addTarget:self action:@selector(addCustomBiaoQianBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:addcustomBiaoQianBtn];
    
    //分割线
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(customBiaoQianLab.frame), self.view.frame.size.width, 1)];
    line1.backgroundColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
    [scrollView addSubview:line1];
    
    //自定义标签的scrollView
    UIScrollView *customBiaoQianScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(line1.frame)+1, self.view.frame.size.width, 10+(btn_h+10)*3)];
    [scrollView addSubview:customBiaoQianScrollView];
    [self makeScrollView:customBiaoQianScrollView andData:_customArray AndTag:1];
    
    
    
    //系统标签的view
    UIView *view2=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(customBiaoQianScrollView.frame), self.view.frame.size.width, 40)];
    view2.backgroundColor=[UIColor whiteColor];
    [scrollView addSubview:view2];
    //系统标签
    UILabel *systemBiaoQianLab=[[UILabel alloc]initWithFrame:CGRectMake(15, view2.frame.origin.y+10, 60, 30)];
    systemBiaoQianLab.text=@"系统标签";
    systemBiaoQianLab.textColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
    systemBiaoQianLab.font=[UIFont systemFontOfSize:20];
    systemBiaoQianLab.frame=CGRectMake(15, view2.frame.origin.y+10, [systemBiaoQianLab calculateWidthWithLable:systemBiaoQianLab], 30);
    [scrollView addSubview:systemBiaoQianLab];
    
    
    //分割线
    UIView *line2=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(systemBiaoQianLab.frame), self.view.frame.size.width, 1)];
    line2.backgroundColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
    [scrollView addSubview:line2];
    
    //系统标签的scrollView
    UIScrollView *systemBiaoQianScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(line2.frame)+1, self.view.frame.size.width, SystemHeight-(CGRectGetMaxY(line2.frame)+1))];
    [scrollView addSubview:systemBiaoQianScrollView];
    [self makeScrollView:systemBiaoQianScrollView andData:_systemArray AndTag:2];
    
    

    
    _customScrollView=customBiaoQianScrollView;
    _systemScrollView=systemBiaoQianScrollView;
    //_myScrollView=myBiaoQianScrollView;
    
    scrollView.contentSize=CGSizeMake(self.view.frame.size.width, CGRectGetMaxY(systemBiaoQianScrollView.frame)+10);
    
    _addCustomBiaoQianBtn=addcustomBiaoQianBtn;
    
    
    
}


//添加自定义标签
-(void)addCustomBiaoQianBtnClick:(UIButton *)sender
{
    NSLog(@"添加自定义标签");
    
    if (_customArray.count>=6) {
        sender.userInteractionEnabled=NO;
        [self.view showPromptMessage:YES and:@"最多只能拥有6个标签"];
        _myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    }else{
        AddCustomBiaoQianViewController *vc=[[AddCustomBiaoQianViewController alloc]init];
        vc.changeData=^(NSDictionary *biaoqianDic){
            for (id subView in _customScrollView.subviews) {
                [subView removeFromSuperview];
            }
            
            [_customArray addObject:biaoqianDic];
            [self makeScrollView:_customScrollView andData:_customArray AndTag:1];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


//启动定时器
-(void)timerRun
{
    if (myTime>=1) {
        [_myTimer invalidate];
        _myTimer=nil;
        myTime=0;
        _addCustomBiaoQianBtn.userInteractionEnabled=YES;
        [self.view showPromptMessage:NO and:nil];
    }else{
        
    }
    myTime++;
}







//添加系统标签
-(void)addSystemBiaoQianBtnClick:(UIButton *)sender
{
    if (_customArray.count<6) {
        for (id subView in _customScrollView.subviews) {
            [subView removeFromSuperview];
        }
        [_customArray addObject:_systemArray[sender.tag-100]];
        
        
        NSLog(@"添加系统标签======%@name======%@",_systemArray[sender.tag-100],_systemArray[sender.tag-100][@"name"]);
        [self addToMyBiaoQian:_systemArray[sender.tag-100]];
        
        [self makeScrollView:_customScrollView andData:_customArray AndTag:1];
        
        [_systemArray removeObjectAtIndex:sender.tag-100];
        for (id subView in _systemScrollView.subviews) {
            [subView removeFromSuperview];
        }
        [self makeScrollView:_systemScrollView andData:_systemArray AndTag:2];
        
        
    }
    
    
    
}

-(void)createNavigation
{
    self.navigationController.navigationBar.hidden=NO;
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"添加标签";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
    
    
//    //完成
//    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//    rightBtn.frame=CGRectMake(0, 0, 40, 30);
//    rightBtn.titleLabel.font=[UIFont systemFontOfSize:12];
//    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
//    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}
////完成编辑
//-(void)rightBtnClick:(UIButton *)sender
//{
//    
//}
//返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    NSArray *arr=[NSArray arrayWithArray:_customArray];
    self.navigationController.navigationBar.hidden=YES;
    self.changeBiaoQian(arr);
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)makeScrollView:(UIScrollView *)scrollView andData:(NSMutableArray *)dataArray AndTag:(NSInteger)tag
{
    CGFloat lab_w=(self.view.frame.size.width-15*3)/2.0;
    CGFloat lab_h=30;
    NSInteger hang=[self calculatingHang:dataArray.count];
    for (int i=0; i<hang; i++) {
        for (int j=0; j<2; j++) {
            if (i*2+j<dataArray.count) {
                
                UIView *view=[[UIView alloc]initWithFrame:CGRectMake(15+(lab_w+15)*j, 10+(lab_h+10)*i, lab_w, lab_h)];
                view.backgroundColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
                view.layer.borderColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1].CGColor;
                view.layer.borderWidth=1.0;
                view.layer.cornerRadius=3.0;
                [scrollView addSubview:view];
                
                UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(2, 0, view.frame.size.width-2, view.frame.size.height)];
                lab.text=dataArray[i*2+j][@"name"];
                lab.font=[UIFont systemFontOfSize:16];
                lab.textColor=[UIColor whiteColor];
                //lab.backgroundColor=[UIColor colorWithRed:87/255.0 green:187/255.0 blue:215/255.0 alpha:1];
                [view addSubview:lab];
                
                if (tag==1) {
                    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame=CGRectMake(view.frame.size.width-20, 5, 20, 20);
                    btn.tag=i*2+j;
                    [btn setBackgroundImage:[UIImage imageNamed:@"app_delete"] forState:UIControlStateNormal];
                    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
                    [view addSubview:btn];
                }else if (tag==2){
                    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame=lab.frame;
                    btn.tag=i*2+j+100;
                    [btn addTarget:self action:@selector(addSystemBiaoQianBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                    [view addSubview:btn];
                }
                
                
                
            }
        }
        scrollView.contentSize=CGSizeMake(self.view.frame.size.width, 10+(lab_h+10)*[self calculatingHang:dataArray.count]);
    }

}

-(void)btnClick:(UIButton *)sender
{
    BOOL isTrue=false;
    for (NSDictionary *dic in _mySystemArray) {
        if ([dic[@"name"] isEqualToString:_customArray[sender.tag][@"name"]]) {
            isTrue=true;
            break;
        }
    }
    [self delteTagData:_customArray[sender.tag]];
    if (isTrue) {
        for (id subView in _customScrollView.subviews) {
            [subView removeFromSuperview];
        }
        [_systemArray addObject:_customArray[sender.tag]];
        [_customArray removeObjectAtIndex:sender.tag];
        
        
        [self makeScrollView:_customScrollView andData:_customArray AndTag:1];
        
        for (id subView in _systemScrollView.subviews) {
            [subView removeFromSuperview];
        }
       // [_systemArray addObject:_mySystemArray[sender.tag]];
        [self makeScrollView:_systemScrollView andData:_systemArray AndTag:2];
    }else{
        for (id subView in _customScrollView.subviews) {
            [subView removeFromSuperview];
        }
        [_customArray removeObjectAtIndex:sender.tag];
        [self makeScrollView:_customScrollView andData:_customArray AndTag:1];
    }
    
    
    
    
//    [_dataArray removeAllObjects];
//    for (NSString *str in _systemArray) {
//        [_dataArray addObject:str];
//    }
//    for (NSString *str in _customArray) {
//        [_dataArray addObject:str];
//    }
//    for (id subView in _myScrollView.subviews) {
//        [subView removeFromSuperview];
//    }
//    [self makeScrollView:_myScrollView andData:_dataArray AndTag:3];
    
    //NSLog(@"======%@",sender.titleLabel.text);
    //sender.backgroundColor=[UIColor yellowColor];
}
-(NSInteger)calculatingHang:(NSInteger)number
{
    NSInteger hang;
    if (number%2==0) {
        hang=number/2;
    }else{
        hang=number/2+1;
    }
    return hang;
}
-(void)viewWillAppear:(BOOL)animated
{
    if (myTime>0) {
        [_myTimer invalidate];
        _myTimer=nil;
        myTime=0;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)addToMyBiaoQian:(NSDictionary *)dataDic
{
    
    NSLog(@"得到的tag=====%@name======%@",dataDic,dataDic[@"name"]);
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager POST:[NSString stringWithFormat:AddToMy,token,dataDic[@"id"]] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"添加标签===%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];
}




-(void)delteTagData:(NSDictionary *)dataDic
{
    NSLog(@"==========id===%@====%@",dataDic[@"id"],dataDic);
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager DELETE:[NSString stringWithFormat:DeleteBiaoQian,token,dataDic[@"id"]] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"删除标签%@==========%@",dic,dic[@"status"][@"msg"]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
